package com.taobao.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.taobao.base.model.RestResponse;
import com.taobao.message.feignclient.UserServiceClient;
import com.taobao.message.mapper.FriendshipsMapper;
import com.taobao.message.mapper.MessagesMapper;
import com.taobao.message.model.dto.MsgPrevDto;
import com.taobao.message.model.dto.UserDto;
import com.taobao.message.model.po.Friendships;
import com.taobao.message.model.po.Messages;
import com.taobao.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


@Service
@Slf4j
public class MessageServiceImpl implements MessageService {


    @Autowired
    private FriendshipsMapper friendshipsMapper;
    @Autowired
    private MessagesMapper messagesMapper;
    @Autowired
    private UserServiceClient userServiceClient;

    private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),  // workQueue
            Executors.defaultThreadFactory(),  // threadFactory
            new ThreadPoolExecutor.CallerRunsPolicy()  // rejectedExecutionHandler
    );


    @Override
    public RestResponse<List<MsgPrevDto>> getMessagePreviewList(String tbId) {

        // 1.获取当前用户所有朋友
        LambdaQueryWrapper<Friendships> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Friendships::getUserId, tbId).or()
                .eq(Friendships::getFriendId, tbId);
        List<Friendships> friendshipsList = friendshipsMapper.selectList(wrapper);

        // 2.根据用户id 和朋友id 查询之间聊天记录(最新那条)
        List<MsgPrevDto> msgPrevDtoList = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(friendshipsList.size());


        for (Friendships friendships : friendshipsList) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Messages messages = messagesMapper.selectByUserIdAndFriendId(friendships.getUserId(), friendships.getFriendId());
                        if (messages != null) {
                            // 朋友id
                            String friendId = friendships.getUserId().equals(tbId) ? friendships.getFriendId() : tbId;
                            // 远程调用，查询朋友信息
                            RestResponse<UserDto> restResponse = userServiceClient.getUserById(friendId);
                            if (restResponse.getCode() == 0) {
                                UserDto friend = restResponse.getResult();
                                MsgPrevDto msgPrevDto = new MsgPrevDto();
                                msgPrevDto.setFriendId(friendId);
                                msgPrevDto.setFriendName(friend.getTbName());
                                msgPrevDto.setFriendAvatar(friend.getHeadimgurl());
                                msgPrevDto.setMessage(messages.getContent());
                                msgPrevDto.setMessageTime(messages.getSendTime().toString());
                                msgPrevDto.setIsRead(messages.getIsRead());
                                msgPrevDtoList.add(msgPrevDto);
                            } else {
                                // 查询失败
                                log.error("查询用户失败");
                            }
                        }
                    } finally {
                        latch.countDown(); // 任务完成，计数减一
                    }
                }
            });
        }
        // 主线程等待所有子线程执行完毕
        try {
            latch.await(); // 等待所有任务完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("主线程等待中断", e);
        }

        return RestResponse.success(msgPrevDtoList);
    }

    @Override
    public RestResponse<List<Messages>> getChatRecord(String tbId, String friendId) {

        List<Messages> messagesList = messagesMapper.getChatRecord(tbId, friendId);

        System.out.println(messagesList);


        return RestResponse.success(messagesList);
    }
}
